import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:memo/state/model/todo.dart';
import 'package:memo/state/work_record_state.dart';
import 'package:provider/provider.dart';

import 'home_page.dart';

class AddTodoPage extends StatefulWidget {
  final Todo todo;

  const AddTodoPage(this.todo);

  @override
  _AddTodoPageState createState() => _AddTodoPageState();
}

class _AddTodoPageState extends State<AddTodoPage> {
  final _noteController = TextEditingController();
  final GlobalKey _formKey = GlobalKey<FormState>();
  TimeOfDay _timeOfDay;
  DateTime _dateTime;
  bool _successFlag, _waringFlag, _errorFlag;

  @override
  void initState() {
    super.initState();
    if (widget.todo == null) {
      _initTodo();
    } else {
      _setTodoValue();
    }
    _timeOfDay = TimeOfDay.fromDateTime(_dateTime);
  }

  @override
  Widget build(BuildContext context) {
    final title = widget.todo == null ? const Text("添加") : const Text("修改");
    return Scaffold(
      appBar: AppBar(
        title: title,
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.symmetric(horizontal: 18.0, vertical: 10.0),
        child: Form(
          key: _formKey, //设置globalKey，用于后面获取FormState
          autovalidate: true, //开启自动校验
          child: Column(
            children: <Widget>[
              const SizedBox(height: 16.0),
              Row(
                children: <Widget>[
                  Flexible(
                    flex: 3,
                    child: InkWell(
                      onTap: () => _selectDate(context, _dateTime),
                      child: InputDecorator(
                        decoration: InputDecoration(
                          border: OutlineInputBorder(),
                          labelText: "日期",
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            Text(DateFormat("yyyy-MM-dd").format(_dateTime)),
                            Icon(
                              Icons.arrow_drop_down,
                              color: Theme.of(context).brightness ==
                                      Brightness.light
                                  ? Colors.grey.shade700
                                  : Colors.white70,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 10.0),
                  Flexible(
                    flex: 2,
                    child: InkWell(
                      onTap: () => _selectTime(
                          context,
                          widget.todo != null
                              ? TimeOfDay.fromDateTime(widget.todo.time)
                              : TimeOfDay.now()),
                      child: InputDecorator(
                        decoration: InputDecoration(
                          border: OutlineInputBorder(),
                          labelText: "时间",
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            Text(_timeOfDay.format(context)),
                            Icon(
                              Icons.arrow_drop_down,
                              color: Theme.of(context).brightness ==
                                      Brightness.light
                                  ? Colors.grey.shade700
                                  : Colors.white70,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20.0),
              _checkBoxRow(),
              const SizedBox(height: 20.0),
              TextFormField(
                maxLines: 5,
                maxLength: 100,
                controller: _noteController,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: "具体",
                  hintText: "具体",
                ),
                validator: (v) {
                  return v.trim().length > 0 ? null : "不能为空";
                },
              ),
              const SizedBox(height: 28.0),
              Row(
                children: <Widget>[
                  Expanded(
                    child: Consumer<WorkRecordState>(
                        builder: (context, workRecordState, _) => RaisedButton(
                              child: Padding(
                                padding: EdgeInsets.all(14.0),
                                child: const Text("保存"),
                              ),
                              onPressed: () async {
                                if ((_formKey.currentState as FormState)
                                    .validate()) {
                                  final time = DateTime(_dateTime.year,
                                          _dateTime.month, _dateTime.day)
                                      .add(Duration(
                                          hours: _timeOfDay.hour,
                                          minutes: _timeOfDay.minute));
                                  widget.todo == null
                                      ? await workRecordState.addTodo(
                                          _noteController.text,
                                          time,
                                          _successFlag,
                                          _waringFlag,
                                          _errorFlag)
                                      : await workRecordState.updateTodo(Todo(
                                          id: widget.todo.id,
                                          type: _convertTypeFlag(),
                                          note: _noteController.text,
                                          time: time));
                                  _noteController.clear();
                                  Navigator.pop(context);
                                }
                              },
                            )),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _selectDate(BuildContext context, DateTime dateTime) async {
    final picked = await showDatePicker(
        context: context,
        initialDate: dateTime,
        firstDate: dateTime.add(Duration(days: -5)),
        lastDate: dateTime.add(Duration(days: 5)));

    if (picked != null) {
      setState(() {
        _dateTime = picked;
      });
    }
  }

  void _selectTime(BuildContext context, TimeOfDay time) async {
    final TimeOfDay picked = await showTimePicker(
      context: context,
      initialTime: time,
    );
    if (picked != null) {
      setState(() {
        _timeOfDay = picked;
      });
    }
  }

  Widget _checkBoxRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        CheckBoxItem(
          value: _successFlag,
          activeColor: successColor,
          text: Text("普通"),
          radius: 20.0,
          valueChanged: (value) {
            setState(() {
              _successFlag = value;
              if (value) {
                _waringFlag = false;
                _errorFlag = false;
              }
            });
          },
        ),
        CheckBoxItem(
          value: _waringFlag,
          activeColor: waringColor,
          text: Text("一般"),
          radius: 20.0,
          valueChanged: (value) {
            setState(() {
              _waringFlag = value;
              if (value) {
                _successFlag = false;
                _errorFlag = false;
              }
            });
          },
        ),
        CheckBoxItem(
          value: _errorFlag,
          activeColor: errorColor,
          text: Text("紧急"),
          radius: 20.0,
          valueChanged: (value) {
            setState(() {
              _errorFlag = value;
              if (value) {
                _successFlag = false;
                _waringFlag = false;
              }
            });
          },
        )
      ],
    );
  }

  void _initTodo() {
    _successFlag = true;
    _waringFlag = false;
    _errorFlag = false;
    _dateTime = DateTime.now();
  }

  void _setTodoValue() {
    _successFlag = TodoType.success == widget.todo.type ? true : false;
    _waringFlag = TodoType.waring == widget.todo.type ? true : false;
    _errorFlag = TodoType.error == widget.todo.type ? true : false;
    _dateTime = widget.todo.time;
    _noteController.text = widget.todo.note;
  }

  TodoType _convertTypeFlag() {
    if (!_successFlag && !_waringFlag && !_errorFlag) {
      return TodoType.success;
    }

    return _successFlag
        ? TodoType.success
        : (_waringFlag ? TodoType.waring : TodoType.error);
  }
}

class CheckBoxItem extends StatelessWidget {
  final bool value;
  final ValueChanged<bool> valueChanged;
  final Text text;
  final double radius;
  final Color activeColor;

  const CheckBoxItem(
      {Key key,
      this.value,
      this.valueChanged,
      this.text,
      this.radius,
      this.activeColor})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Checkbox(
          value: value,
          activeColor: activeColor, //选中时的颜色
          onChanged: valueChanged,
        ),
        text,
      ],
    );
  }
}
